// import { h, defineComponent,defineAsyncComponent, Component, } from 'vue'
// import type {  ComponentChild } from './type'
// import { makeMap } from '@/utils/index'
// import {
//   ElInput,
//   ElSelect,
//   ElOption,
//   ElRadioGroup,
//   ElRadio,
//   ElRadioButton,
//   ElCheckboxGroup,
//   ElCheckbox,
//   ElCheckboxButton,
//   ElUpload,
//   ElButton,
//   ElIcon
// } from 'element-plus'
// 参考https://github.com/vuejs/vue/blob/v2.6.10/src/platforms/web/server/util.js

import { h, defineComponent, defineAsyncComponent } from 'vue'
import { makeMap } from '@/utils/index'

const isAttr = makeMap(
  'accept,accept-charset,accesskey,action,align,alt,async,autocomplete,' +
    'autofocus,autoplay,autosave,bgcolor,border,buffered,challenge,charset,' +
    'checked,cite,class,code,codebase,color,cols,colspan,content,http-equiv,' +
    'name,contenteditable,contextmenu,controls,coords,data,datetime,default,' +
    'defer,dir,dirname,disabled,download,draggable,dropzone,enctype,method,for,' +
    'form,formaction,headers,height,hidden,high,href,hreflang,http-equiv,' +
    'icon,id,ismap,itemprop,keytype,kind,label,lang,language,list,loop,low,' +
    'manifest,max,maxlength,media,method,GET,POST,min,multiple,email,file,' +
    'muted,name,novalidate,open,optimum,pattern,ping,placeholder,poster,' +
    'preload,radiogroup,readonly,rel,required,reversed,rows,rowspan,sandbox,' +
    'scope,scoped,seamless,selected,shape,size,type,text,password,sizes,span,' +
    'spellcheck,src,srcdoc,srclang,srcset,start,step,style,summary,tabindex,' +
    'target,title,type,usemap,value,width,wrap'
)

export default defineComponent({
  name: 'DynamicRenderer',
  props: {
    conf: {
      type: Object as () => any,
      required: true
    }
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    // 异步加载 Element Plus 组件
    const componentMap: Record<string, any> = {
      'el-input': defineAsyncComponent(() => import('element-plus').then((m) => m.ElInput)),
      'el-input-number': defineAsyncComponent(() =>
        import('element-plus').then((m) => m.ElInputNumber)
      ),
      'el-select': defineAsyncComponent(() => import('element-plus').then((m) => m.ElSelect)),
      'el-option': defineAsyncComponent(() => import('element-plus').then((m) => m.ElOption)),
      'el-radio-group': defineAsyncComponent(() =>
        import('element-plus').then((m) => m.ElRadioGroup)
      ),
      'el-radio': defineAsyncComponent(() => import('element-plus').then((m) => m.ElRadio)),
      'el-radio-button': defineAsyncComponent(() =>
        import('element-plus').then((m) => m.ElRadioButton)
      ),
      'el-checkbox-group': defineAsyncComponent(() =>
        import('element-plus').then((m) => m.ElCheckboxGroup)
      ),
      'el-checkbox': defineAsyncComponent(() => import('element-plus').then((m) => m.ElCheckbox)),
      'el-checkbox-button': defineAsyncComponent(() =>
        import('element-plus').then((m) => m.ElCheckboxButton)
      ),
      'el-switch': defineAsyncComponent(() => import('element-plus').then((m) => m.ElSwitch)),
      'el-date-picker': defineAsyncComponent(() =>
        import('element-plus').then((m) => m.ElDatePicker)
      )
    }
    const vModel = (dataObject: any, defaultValue: any) => {
      dataObject.props.modelValue = defaultValue // 使用 modelValue 而不是 value
      dataObject.props['onUpdate:modelValue'] = (val: any) => {
        emit('update:modelValue', val)
      }
    }

    const renderComponent = () => {
      const component = componentMap[props.conf.tag]
      if (!component) {
        return h('div', `未知组件: ${props.conf.tag}`)
      }

      const dataObject: Record<string, any> = {
        attrs: {},
        props: {},
        on: {},
        style: {}
      }

      const confClone = JSON.parse(JSON.stringify(props.conf))
      let children: any[] = []
      // 处理不同类型的子组件
      switch (props.conf.tag) {
        case 'el-radio-group':
          if (confClone.options) {
            const RadioComponent = componentMap['el-radio']
            children = confClone.options.map((option: any) =>
              h(
                RadioComponent,
                {
                  key: option.value,
                  label: option.value
                },
                () => option.label
              )
            )
          }
          break

        case 'el-checkbox-group':
          if (confClone.options) {
            const CheckboxComponent = componentMap['el-checkbox']
            children = confClone.options.map((option: any) =>
              h(
                CheckboxComponent,
                {
                  key: option.value,
                  label: option.value
                },
                () => option.label
              )
            )
          }
          break

        case 'el-select':
          if (confClone.options) {
            const OptionComponent = componentMap['el-option']
            children = confClone.options.map((option: any) =>
              h(OptionComponent, {
                key: option.value,
                label: option.label,
                value: option.value
              })
            )
          }
          break
      }
      // 处理属性分配
      Object.keys(confClone).forEach((key) => {
        const val = confClone[key]
        if (key === 'vModel') {
          vModel(dataObject, confClone.defaultValue)
        } else if (dataObject[key]) {
          dataObject[key] = val
        } else if (!isAttr(key)) {
          dataObject.props[key] = val
        } else {
          dataObject.attrs[key] = val
        }
      })
      return h(component, { ...dataObject.attrs, ...dataObject.props, ...dataObject.on }, children)
    }

    return renderComponent
  }
})
